<template>
  <view class="edit-page post-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="岗位名称" name="postName" required>
          <uni-easyinput
              v-model="form.postName"
              placeholder="请输入岗位名称"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="岗位编码" name="postCode" required>
          <uni-easyinput
              v-model="form.postCode"
              placeholder="请输入岗位编码"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="显示顺序" name="postSort" required>
          <uni-number-box
              v-model="form.postSort"
              :min="0"
              :max="999"
              :disabled="!canEdit">
          </uni-number-box>
        </uni-forms-item>

        <uni-forms-item label="岗位状态" name="status">
          <BottomSelect
              v-model="form.status"
              :options="statusOptions"
              value-field="value"
              label-field="text"
              placeholder="请选择岗位状态"
              title="选择岗位状态"
              :disabled="!canEdit">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注信息"
              :auto-height="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addPost, getPost, updatePost} from '@/api/system/post'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()

// 页面参数
const pageType = ref('add')
const postId = ref(null)
const submitting = ref(false)

// 计算属性
const pageTitle = computed(() => {
  switch (pageType.value) {
    case 'add':
      return '新增岗位'
    case 'edit':
      return '编辑岗位'
    case 'view':
      return '查看岗位'
    default:
      return '岗位管理'
  }
})

const isView = computed(() => pageType.value === 'view')
const canEdit = computed(() => pageType.value === 'add' || pageType.value === 'edit')

// 表单数据
const form = reactive({
  postId: undefined,
  postName: '',
  postCode: '',
  postSort: 0,
  status: '0',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  postName: {
    rules: [
      {required: true, errorMessage: '岗位名称不能为空'},
      {minLength: 2, maxLength: 50, errorMessage: '岗位名称长度应为2-50位'}
    ]
  },
  postCode: {
    rules: [
      {required: true, errorMessage: '岗位编码不能为空'},
      {minLength: 2, maxLength: 64, errorMessage: '岗位编码长度应为2-64位'},
      {pattern: /^[a-zA-Z0-9_-]+$/, errorMessage: '岗位编码只能包含字母、数字、下划线和短横线'}
    ]
  },
  postSort: {
    rules: [
      {required: true, errorMessage: '显示排序不能为空'},
      {min: 0, max: 999, errorMessage: '显示排序必须在0-999之间'}
    ]
  }
})

const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
])

const formRef = ref()

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  pageType.value = options.mode || 'add'

  if (options.postId) {
    postId.value = options.postId
    if (pageType.value === 'edit' || pageType.value === 'view') {
      getPostData()
    }
  }

  // 设置页面标题
  const titleMap = {
    add: '新增岗位',
    edit: '编辑岗位',
    view: '查看岗位'
  }
  uni.setNavigationBarTitle({
    title: titleMap[pageType.value] || '岗位管理'
  })
})

// 获取岗位数据
async function getPostData() {
  try {
    const response = await getPost(postId.value)
    if (response.code === 200) {
      const postData = response.data
      Object.assign(form, postData)
    }
  } catch (error) {
    console.error('获取岗位数据失败:', error)
    proxy.$modal.showToast('获取岗位数据失败')
  }
}

// 提交表单
async function submitForm() {
  if (submitting.value) return

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    let response
    if (pageType.value === 'add') {
      response = await addPost(form)
    } else if (pageType.value === 'edit') {
      response = await updatePost(form)
    }

    if (response.code === 200) {
      proxy.$modal.showToast(pageType.value === 'add' ? '新增成功' : '修改成功')
      goBack()
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('提交失败')
  } finally {
    submitting.value = false
  }
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';

// 岗位编辑页面特定样式
.post-edit-page {
  // 可以添加岗位特有的样式覆盖
}
</style> 